#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "process.h"

/*
 * This function logs all events that occur in the
 * program. All events are written to the main log,
 * and each event is written to its specific event
 * log as well. The type of event that is being
 * logged is passed to the function by two strings.
 */

void log_queue(char *operation, int pid, enum State process_state)
{
	//int all_log, queue_log;
	FILE *all_log, *queue_log;
	char *prefix;
	char *queue;

	switch (process_state)
	{
	case New:
		queue = "New";
		break;

	case Ready:
		queue = "Ready";
		break;

	case Waiting:
		queue = "Waiting";
		break;

	case Running:
		queue = "Running";
		break;

	case Terminated:
		queue = "Terminated";
		break;

	default:
		queue = "Foo";
		break;
	}

	if (operation[0] == 'E')
	{
		prefix = "[Enqueue] ";
	} else if (operation[0] == 'D')
	{
		prefix = "[Dequeue] ";
	}

  	all_log = fopen("all.log", "a");
	queue_log = fopen("queue.log", "a");
	
	fprintf(all_log, "%s Process %d %squeued %s\n", prefix, pid, operation, queue);
	fprintf(queue_log, "%s Process %d %squeued %s\n", prefix, pid, operation, queue);

	fclose(all_log);
	fclose(queue_log);
}

void log_error(char *error)
{
	FILE *all_log, *err_log;
	char *prefix = "[Error]  ";

	all_log = fopen("all.log", "a");
	err_log = fopen("error.log", "a");

    fprintf(all_log, "%s %s\n", prefix, error);
    fprintf(err_log, "%s %s\n", prefix, error);

	fclose(all_log);
	fclose(err_log);
}

void log_notice(char *notice)
{
	FILE *all_log, *not_log;
	char *prefix = "[Notice] ";

	all_log = fopen("all.log", "a");
	not_log = fopen("notice.log", "a");

	fprintf(all_log, "%s Resource %s was freed\n", prefix, notice);
	fprintf(not_log, "%s Resource %s was freed\n", prefix, notice);
	
	fclose(all_log);
	fclose(not_log);
}

void log_resource(char *resource, int pid)
{
	FILE *all_log, *not_log;
	char *prefix = "[Notice] ";

	all_log = fopen("all.log", "a");
	not_log = fopen("notice.log", "a");

	fprintf(all_log, "%s Process <%d> has resource %s\n", prefix, pid, resource);
	fprintf(not_log, "%s Process <%d> has resource %s\n", prefix, pid, resource);
	
	fclose(all_log);
	fclose(not_log);
}

void log_waiting(char *resource, int pid)
{
	FILE *all_log, *not_log;
	char *prefix = "[Notice] ";

	all_log = fopen("all.log", "a");
	not_log = fopen("notice.log", "a");

	fprintf(all_log, "%s Process <%d> is waiting on resource %s\n", prefix, pid, resource);
	fprintf(not_log, "%s Process <%d> is waiting on resource %s\n", prefix, pid, resource);
	
	fclose(all_log);
	fclose(not_log);
}
